<template>
  <uni-nav-bar title="安蓝环保" :fixed="true" statusBar></uni-nav-bar>
  <swiperList></swiperList>
  <view class="package space-between" style="padding:0rpx 15rpx 0rpx 0px;">
    <uni-notice-bar single scrollable speed="50" :text="text" background-color="#fff" color="#333"></uni-notice-bar>
    <image :src="audio?horn2:horn1" mode="" style="width:40rpx;height:40rpx;" @click="broadcast()"></image>
  </view>
  <view class="package">
    <view>请提供以下信息 以便于我们更及时的为您服务</view>
    <view class="text">车牌号</view>
    <view class="space-between card">
      <view v-for="(item) in car" :style="{display:car?'block':'none'}" @click="openPlatePicker()">{{item}}</view>
      <view v-for="(item) in 7" :style="{display:car?'none':'block'}" @click="openPlatePicker()"></view>
      <view style="width: 56rpx;background: rgba(93, 214, 198, .1);" @click="changes()" class="column">
        <text style="font-size: 20rpx;color: #1B91FF;line-height: 40rpx;">切换</text>
        <image src="../../static/mine/sj.png" mode="" style="width:20rpx;height:20rpx;"></image>
      </view>
    </view>
    <view class="text">手机号</view>
    <input class="uni-input"
      :placeholder="userInfo.mobile?userInfo.mobile.replace(/^(\d{3})(\d{4})/g, '$1 $2 '):'请输入手机号'" v-model="phone"
      placeholder-style="color:#333" @input="onCallInput" />
    <view class="text">时间</view>
    <view class="space-between">
      <view>{{num>1?'指定时间':'立即配送'}}</view>
      <view style="font-size: 24rpx;" @click="openTimePicker()">{{num>1?`大约${time}送达 >`:'您也可以预约时间配送 >'}}</view>
    </view>
    <view style="font-size: 22rpx;color: #666;margin-top:10rpx;" v-if="jisuan">
      <image src="../../static/icon/tb.png" mode="" style="width:30rpx;height:30rpx;"></image>
      {{jisuan}}
    </view>
    <view class="text space-between" @click="navTo('reservation/addressList?name='+locName)">位置
      <uni-icons type="location-filled" size="23" color="#1B91FF"></uni-icons>
    </view>
    <view>{{locName}}</view>
    <view class="but" @click="submit()">提交预约</view>
    <view class="tel" @click="telCall('400-109-1606')">客服电话：400-109-1606</view>
  </view>
  <!-- 车牌弹框 -->
  <VehiclePlatePad v-if="isShowPlatePad" @cancel="isShowPlatePad = false" @confirm="confirmPlate" />
  <!-- 预约时间弹框 -->
  <TimePicker ref="TimePickerRef" @jisuanScore="jisuanScores" />
  <!-- 车辆弹框 -->
  <CarPop ref="carpup" @berplate="berplate"></CarPop>
  <!-- 当前位置经纬度 -->
  <Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
  import * as AMapLoader from '@amap/amap-jsapi-loader';
  import { navTo, redirectTo } from '@/utils/navigator';
  import VehiclePlatePad from '@c/common/VehiclePlatePads.vue';
  import TimePicker from '@c/reservation/TimePicker.vue';
  import swiperList from '@c/reservation/swiper.vue';
  import Lotlats from '@c/team/Lotlat.vue';
  import CarPop from '@c/reservation/carPop.vue';
  import { ref } from 'vue';
  import { horn1, horn2 } from '@/utils/Static';
  import { telCall } from '@/utils/copyText';
  import { useUserStore } from '@/stores/user';
  import { toPublish } from '@mqtt';
  import { showLoading, errorToast, successToast } from '@/utils/prompt';
  // getHistoryAddress
  import { jisuanScore } from '@/gql/reservation';
  import { getSubscribeMp3, authorMe } from '@/gql/user';
  import { onShow, onUnload, onLoad } from '@dcloudio/uni-app';
  import { getDriverID } from '@/stores/driverID';
  const driver_id = getDriverID();
  const text = ref()
  const userInfo = useUserStore();
  const isShowPlatePad = ref(false); //添加车牌弹框
  const numberplate = ref(''); //车牌号
  const car = ref()
  const delivery_time = ref()
  const jisuan = ref('')
  const time = ref()
  const phon = ref()

  const longitude = ref()
  const latitude = ref()
  const locName = ref('')
  const phone = ref()
  const TimePickerRef = ref(null);
  const carpup = ref(null)
  const audio = ref(false)
  const innerAudioContext = ref(null)
  const num = ref(0)
  const chat_id = ref()

  onLoad((pearm) => {
    chat_id.value = pearm.chat_id
    innerAudioContext.value = uni.createInnerAudioContext()
    setTimeout(() => {
      TimePickerRef.value.init();
      carpup.value.init()
      // init()
    }, 500)
  })
  onShow(() => {
    const lost = uni.getStorageSync('Appointment')
    longitude.value = lost.longitude
    latitude.value = lost.latitude
    locName.value = lost.locName
  })
  function onCallInput(event : any) {
    const { detail } = event;
    let value = detail.value.replace(/\D/g, '').substr(0, 11) // 不允许输入非数字字符，超过11位数字截取前11
    let len = value.length
    if (len > 3 && len < 8) {
      value = value.replace(/^(\d{3})/g, '$1 ')
    } else if (len >= 8) {
      value = value.replace(/^(\d{3})(\d{4})/g, '$1 $2 ')
    }
    phone.value = value
  }
  // function init() {
  //   showLoading()
  //   const payload = {
  //     query: getHistoryAddress,
  //     variables: {
  //       driver_id,
  //     },
  //   };
  //   toPublish(
  //     'ql/plug/getHistoryAddress',
  //     payload,
  //     (obj : any) => {
  //       uni.hideLoading();
  //       const { getHistoryAddress } = obj.data;
  //       if (getHistoryAddress.length > 0) {
  //         longitude.value = getHistoryAddress[0].longitude
  //         latitude.value = getHistoryAddress[0].latitude
  //         locName.value = getHistoryAddress[0].address
  //       }
  //     }
  //   );
  // }
  audios()
  function audios() {
    showLoading()
    const payload = {
      query: getSubscribeMp3
    };
    toPublish(
      'ql/driver/getSubscribeMp3',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { getSubscribeMp3 } = obj.data;
        innerAudioContext.value.loop = true;
        innerAudioContext.value.src = getSubscribeMp3.mp3;
        innerAudioContext.value.autoplay = true;
        innerAudioContext.value.onPlay(() => {
          console.log('是否可以播放')
        })
      }
    );
  }
  function broadcast() {
    audio.value = !audio.value
    if (innerAudioContext.value.paused) {
      innerAudioContext.value.play()
    } else {
      innerAudioContext.value.pause()
    }
  }
  // 公告
  notice()
  function notice() {
    const payload = {
      query: authorMe,
      variables: {
        code: 'yuyuegonggao',
      },
    };
    toPublish('ql/driver/getMyblock', payload, (obj : any) => {
      const { data } = obj;
      text.value = data.get_myblock.content;
    });
  }
  /**
   * 正则手机号码
   */
  function phoneTel() {
    const mobile = /^1[3-9]\d{9}$/;
    phon.value = phone.value ? phone.value.replace(/\s*/g, "") : ''
    const userPhone = phon.value ? phon.value : userInfo.mobile;
    return mobile.test(userPhone);
  }
  // 提交预约
  function submit() {
    phon.value = phone.value ? phone.value.replace(/\s*/g, "") : ''
    const mobile = phon.value ? phon.value : userInfo.mobile;
    if (!numberplate.value) {
      errorToast('请输入车牌号')
      return
    }
    if (!mobile) {
      errorToast('请输入手机号码')
      return
    } else if (!phoneTel()) {
      errorToast('请输入正确的手机号码');
      return;
    }
    if (!locName.value) {
      errorToast('暂无法获取您的位置信息 请打开GPS定位');
      return;
    }
    showLoading()
    const payload = {
      chat_id: chat_id.value,
      driver_id,
      cart_code: numberplate.value,
      mobile,
      address: locName.value,
      longitude: longitude.value,
      latitude: latitude.value,
      delivery_type: num.value === 1 ? 1 : 2,
      delivery_time: delivery_time.value,
    };
    toPublish('plug/addSubscribeLog',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, msg, data } = obj;
        if (code === 1) {
          successToast(msg)
          redirectTo('reservation/details?id=' + data)
        } else {
          errorToast(msg)
        }
      }
    );
  }

  /**
   * 打开/关闭车牌弹框
   */
  function openPlatePicker() {
    isShowPlatePad.value = true
  }
  function confirmPlate(plate : string) {
    numberplate.value = plate;
    car.value = plate.split('')
    isShowPlatePad.value = false;
  }
  /**
    * 获取当前城市信息
    * @param  lat 当前位置的纬度
    * @param  lot 当前位置的经度
    * @return MapPage 修改地图页面的first状态
    */
  function position(lat : number, lot : number) {
    console.log(JSON.stringify(lat) + '*****')
    if (locName.value) {
      return
    }
    longitude.value = lot;
    latitude.value = lat;
    getPositionByLonLats(lot, lat)
  }
  function getPositionByLonLats(lng : number, lat : number) {
    AMapLoader.load({
      key: '28c93d7518383bfa130b6c7cd239c331', // 申请好的Web端开发者Key，首次调用 load 时必填  
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Geocoder', 'AMap.Geolocation'] //插件列表
    })
      .then(AMap => {
        const lnglat = [lng, lat]
        const geocoder = new AMap.Geocoder()
        geocoder.getAddress(lnglat, function (status, result) {
          console.log(status + '*****' + result.regeocode)
          if (status === 'complete' && result.regeocode) {
            locName.value = result.regeocode.formattedAddress
          } else {
            console.log('根据经纬度查询地址失败')
          }
        })
      })
  }
  // 预约时间
  function jisuanScores(tim : any, date : string, day : string) {
    num.value++
    delivery_time.value = tim
    time.value = day ? day + '-' + date : date
    showLoading()
    const payload = {
      query: jisuanScore,
      variables: {
        time: tim
      },
    };
    toPublish(
      'ql/plug/jisuanScore',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { jisuanScore } = obj.data;
        jisuan.value = jisuanScore.text
      }
    );
  }
  // 车牌号
  function berplate(cars : string) {
    numberplate.value = cars;
    car.value = cars.split('')
  }
  // TimePicker
  function openTimePicker() {
    TimePickerRef.value.open();
  }
  function changes() {
    carpup.value.open()
  }
  onUnload(() => {
    innerAudioContext.value.pause()
    uni.removeStorageSync('Appointment');
  })
</script>
<style scoped lang="less">
  .ad-img-swiper {
    width: 100%;
    height: 327rpx;
  }

  .text {
    font-size: 26rpx;
    color: #666666;
    margin: 15rpx 0px;
  }

  .card {
    view {
      width: 75rpx;
      height: 90rpx;
      background: rgba(27, 145, 255, .1);
      border-radius: 10rpx;
      text-align: center;
      line-height: 90rpx;
    }
  }

  .but {
    width: 530rpx;
    height: 96rpx;
    background: #1B91FF;
    border-radius: 48rpx;
    text-align: center;
    line-height: 96rpx;
    color: #FFFFFF;
    margin: 50rpx auto 20rpx;
  }

  .tel {
    width: 100%;
    font-size: 24rpx;
    color: #666666;
    text-align: center;
  }
</style>
<style>
  .package>>>.uni-noticebar {
    margin-bottom: 0px;
    border-radius: 5px;
  }
</style>